#include "../include/CServer.h"
#include "../include/conf_reader.h"
#include"../include/statusServer_client_rpc.h"
#include "../include/global.h"
#include "../include/user_list_manger.h"
#include "../include/rpc_server.h"
#include <thread>
int main()
{



    boost::asio::io_context context_for_CServer;
    u_short port=std::atoi(conf_reader::get_conf_reader_instance()->get_value_from_key("local_bind_port","12345"));

    {
        std::string ip=conf_reader::get_conf_reader_instance()->get_value_from_key("local_host","192.168.174.139");
        std::string s_port=conf_reader::get_conf_reader_instance()->get_value_from_key("local_bind_port","12345");
        std::string rpc_service_address=conf_reader::get_conf_reader_instance()->get_value_from_key("rpc_service_address","192.168.174.139:12346");
        user_list_manger::get_instance()->char_server_field=ip+":"+s_port;
        user_list_manger::get_instance()->user_list_key=USER_LIST_PREFIX+ip+":"+s_port;
        user_list_manger::get_instance()->rpc_service_address=rpc_service_address;
    }
   
    std::shared_ptr<CServer>server(new CServer(context_for_CServer,port));
    server->start_accept();
    //向状态服务器注册信息
    if(!(statusServer_client_rpc::get_instance()->register_chat_server())){
        std::cout<<"向状态服务注册失败！！"<<std::endl;
        return 1;
    }
    
    std::thread _thread([](){
        rpc_server::get_instance()->start();
    });


    boost::asio::signal_set signals(context_for_CServer,SIGINT,SIGTERM);
    signals.async_wait([&context_for_CServer,&_thread](const boost::system::error_code& error, int signal_number){
        if(error){
            std::cout<<"信号触发发生异常！！"<<error.what()<<std::endl; //几乎不可能发生
        }
        statusServer_client_rpc::get_instance()->delete_chat_server();  //从状态服务器里删除对应的chat_server信息
        rpc_server::get_instance()->stop();
        _thread.join();
        context_for_CServer.stop();
    });
    context_for_CServer.run();


    return 0;
}